package com.yuzhitong.shapi.util;


import android.app.Activity;
import android.content.res.Resources;
import android.view.View;
import android.widget.FrameLayout;


/**
 * @date: 2018/6/29
 * @Description:AndroidBug5497Workaround 解决webview弹出软键盘后，编辑框不能被顶起的bug
 */
public class AndroidBugWorkaround {

    private final Activity activity;
    // For more information, see https://code.google.com/p/android/issues/detail?id=5497
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
    private final View mChildOfContent;
    private int usableHeightPrevious;
    private final FrameLayout.LayoutParams frameLayoutParams;

    private AndroidBugWorkaround(Activity activity) {
        this.activity = activity;

        FrameLayout content = activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(this::possiblyResizeChildOfContent);
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    }

    public static void assistActivity(Activity activity) {
        new AndroidBugWorkaround(activity);
    }

    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight(); //可利用显示的区域

        if (usableHeightNow != usableHeightPrevious) {

            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();//获取屏幕的高度

            int heightDifference = usableHeightSansKeyboard - usableHeightNow;//
            if (heightDifference > (usableHeightSansKeyboard / 4)) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // keyboard probably just became hidden

//                frameLayoutParams.height = usableHeightSansKeyboard;
                frameLayoutParams.height = usableHeightNow;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return mChildOfContent.getRootView().getHeight() - height;
    }

}
